package springboot.kafka.util;

import org.graylog2.syslog4j.Syslog;
import org.graylog2.syslog4j.SyslogIF;

import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.util.List;

public class UDPSend {
    public static void main(String[] args) {
        DatagramSocket ds = null;
        try {
            //1、创建Socket对象
            ds = new DatagramSocket();
            //2、创建数据
            byte[] bys = "hello socketsss".getBytes();
            InetAddress adress = InetAddress.getByName("192.168.182.212");//括号里面填写接收端的ip地址
            DatagramPacket dp = new DatagramPacket(bys, bys.length, adress, 5000);
            //3、发送数据
            ds.send(dp);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //4、关闭发送
            if (ds != null) {
                ds.close();
            }
        }
    }


    public static void sendUdp(List<String> messageList, String address, Integer port) {
        DatagramSocket ds = null;
        try {
            for (String message : messageList) {
                //1、创建Socket对象
                ds = new DatagramSocket();
                //2、创建数据
                byte[] bys = message.getBytes();
                InetAddress adress = InetAddress.getByName(address);//括号里面填写接收端的ip地址
                DatagramPacket dp = new DatagramPacket(bys, bys.length, adress, port);
                //3、发送数据
                ds.send(dp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //4、关闭发送
            if (ds != null) {
                ds.close();
            }
        }
    }


    public static void generate(List<String> messageList, String address, Integer port) {
        SyslogIF syslog = Syslog.getInstance("udp");
        syslog.getConfig().setHost(address);
        syslog.getConfig().setPort(port);
        try {
            for (String str : messageList) {
                syslog.log(0, URLDecoder.decode(str, "utf-8"));
            }
            System.out.println("数据发送成功");
        } catch (UnsupportedEncodingException e) {
            System.out.println("generate log get exception " + e);
        }
    }


}

